<template>
  <el-dialog title="分配角色" :visible="showDialog" @close="btnCancel">
    <el-checkbox-group v-model="userRolesId">
      <el-checkbox v-for="item in allRoles" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6" style="text-align:center">
        <el-button size="small" type="primary" :loading="loading" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getAllRoleList, saveUserRole } from '@/api/role'
import { getDetailInfo } from '@/api/user'
export default {
  name: 'AssignRole',
  props: {
    showDialog: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      id: '', // 用户id
      allRoles: [], // 所有角色列表
      userRolesId: [], // 用户角色列表
      loading: false
    }
  },
  created() {
    this.getAllRoleList()
  },
  methods: {
    // 获取所有角色
    async getAllRoleList() {
      const { rows } = await getAllRoleList({ page: 1, pagesize: 20 })
      this.allRoles = rows
    },
    // 根据id获取角色信息
    async getDetailInfo(id) {
      try {
        const { roleIds } = await getDetailInfo(id)
        this.userRolesId = roleIds
        this.id = id
      } catch (error) {
        console.log(error)
      }
    },
    btnCancel() {
      this.$parent.showDialog = false
    },
    // 更新用户角色
    async btnOK() {
      this.loading = true
      await saveUserRole({
        id: this.id,
        roleIds: this.userRolesId
      })
      this.loading = false
      this.$message.success('修改用户权限成功')
      this.$parent.showDialog = false
    }
  }
}
</script>

<style>

</style>
